<?php
namespace App\Adshopuser\Controllers;
use App\Adshopuser\Models\BShopAppConfig;
use App\Adshopuser\Models\BShopGoodsCategory;
use App\Adshopuser\Models\BShopGoods;
use App\Adshopuser\Models\BShopSkuValue;
use App\Adshopuser\Models\BShopGoodsSku;
use App\Adshopuser\Models\BShopSkuModel;
use App\Adshopuser\Models\BShopSkuModelKey;
use App\Adshopuser\Models\BShopSkuKey;
use App\Adshopuser\Models\BshopUsersInfo;
use Common\Common;
use Common\ControllerAdshopBase;
use Common\Models\BShopUsers;
use Phalcon\Paginator\Adapter\Model as PaginatorModel;
use Services\Adshopuser\ShopgoodsServices;
use ServicesApi\Request\AddEditGoodsRequest;

class ShopgoodsController extends ControllerAdshopBase
{

    public function initialize()
    {
        parent::initialize();
    }


    //获取分类
    public function categoryGoodsListAction()
    {
        $ShopgoodsServices = new ShopgoodsServices();
        $responseResult = $ShopgoodsServices->getCategoryList($this->params['shop_id']);
        if(!$responseResult['status']){
            $this->fail(-1,$responseResult['msg']);
        }
        $this->ok($responseResult['data']);
    }

    /**
     * 商品上下架
     */
    public function setShelfAction()
    {
        if (!isset($this->params['goods_id']) || empty($this->params['goods_id'])) {
            $this->fail(-1, '缺少商品ID');
        }
        $goodsDb = new BShopGoods();
        $info    = $goodsDb->findFirstById($this->params['goods_id']);
        if (!$info) {
            $this->fail(-1, '缺少商品不存在');
        }
        $info->status     = $info->status == 1 ? 0 : 1;
        $info->updated_at = date('Y-m-d H:i:s');
        if (!$info->save()) {
            $this->fail(-1, '修改失败');
        }
        $this->ok('操作成功!');
    }

    /**
     * 商品列表
     */
    public function listGoodsAction()
    {
        $this->params['page']  = $this->params['page'] ? $this->params['page'] : 1;
        $this->params['limit'] = $this->params['limit'] ? $this->params['limit'] : 10;
        $goodsDb               = new BShopGoods();
        $result                = $goodsDb->lists($this->params);
        $this->ok($result);
    }

    /**
     * 商品详情
     */
    public function onlineGoodsInfoAction()
    {
        if(!isset($this->params['goods_id']) || empty($this->params['goods_id'])){
            $this->fail(-1,"商品ID不能为空");
        }
        $ShopGoodsService = new ShopgoodsServices();
        $responseResult = $ShopGoodsService->onlineGoodsInfo($this->params['goods_id']);
        if(!$responseResult['status']){
            $this->fail(-1,$responseResult['msg']);
        }
        $this->ok($responseResult['data']);
    }

    /**
     * 编辑商品
     */
    public function addEditGoodsAction()
    {
        $addEditGoodsRequest = new AddEditGoodsRequest();
        $requestResult = $addEditGoodsRequest->goodsVerification($this->params);
        if(!$requestResult['status']){
            $this->fail(-1,$requestResult['msg']);
        }
        $shopgoodsServices = new ShopgoodsServices();
        $responseResult = $shopgoodsServices->addEditGoods($this->params);
        if(!$responseResult['status']){
            $this->fail($responseResult['msg']);
        }
        $this->ok($responseResult['msg']);
    }


    /**
     * 编辑模型规格
     */
    public function addModelAction()
    {
        $params = $this->params;
        if (!isset($params['model_name']) && empty($params['model_name'])) {
            $this->fail(-1, '缺少参数model_name');
        }
//        $params = [
//            'id'         => '0',
//            'model_name' => '衣服',
//            'list'       => [
//                [
//                    'key_name' => '颜色',
//                    'value'    => [
//                        ['value_name' => '红色'],
//                        ['value_name' => '红色'],
//                    ]
//                ],
//                [
//                    'key_name' => '尺寸',
//                    'value'    => [
//                        ['value_name' => '红色'],
//                        ['value_name' => '红色'],
//                        ['value_name' => '红色'],
//                    ]
//                ],
//            ]
//        ];
        $msg = $this->verification($this->params);
        if ($msg !== true) {
            $this->fail(-1, $msg);
        }
        $this->dbMaster->begin();
        $date = date('Y-m-d H:i:s');

        $b_shop_sku_model     = new BShopSkuModel();
        $b_shop_sku_model_key = new BShopSkuModelKey();

        if (is_numeric($params['m_id'])) {
            $b_shop_sku_modelInfo = $b_shop_sku_model->findFirstById($params['m_id']);
            if (!$b_shop_sku_modelInfo) {
                $this->fail(-1, '修改模型未找到!');
            }
            $b_shop_sku_modelInfo->name       = $params['model_name'];
            $b_shop_sku_modelInfo->created_at = date('Y-m-d H:i:s');
            if (!$b_shop_sku_modelInfo->save()) {
                $this->dbMaster->rollback();
                $this->fail(-1, '模型编辑失败!');
            }

            if (!$b_shop_sku_model_key->find('m_id = ' . $params['m_id'])->delete()) {
                $this->dbMaster->rollback();
                $this->fail(-1, '模型修改失败!');
            }

        } else {
            $b_shop_sku_model->name       = $params['m_id'];
            $b_shop_sku_model->created_at = $date;
            if (!$b_shop_sku_model->save()) {
                $this->dbMaster->rollback();
                $this->fail(-1, '模型添加失败!');
            }
            $params['id'] = $b_shop_sku_model->id;
        }

        $kidArr = [];
        foreach ($params['list'] as $val) {
            //$val                        = json_decode($val, true);
            $b_shop_sku_key             = new BShopSkuKey();
            $b_shop_sku_key->key_name   = $val['key_name'];
            $b_shop_sku_key->created_at = $date;
            $b_shop_sku_key->updated_at = $date;
            if (!$b_shop_sku_key->save()) {
                $this->dbMaster->rollback();
                $this->fail(-1, '规格名编辑失败!');
            }
            $kidArr[] = $b_shop_sku_key->id;
            foreach ($val['value'] as $val) {
                $b_shop_sku_value             = new BShopSkuValue();
                $b_shop_sku_value->key_id     = $b_shop_sku_key->id;
                $b_shop_sku_value->value_name = $val;
                $b_shop_sku_value->created_at = $date;
                $b_shop_sku_value->updated_at = $date;
                if (!$b_shop_sku_value->save()) {
                    $this->dbMaster->rollback();
                    $this->fail(-1, '规格值编辑失败!');
                }
            }
        }
        foreach ($kidArr as $kVal) {
            $b_shop_sku_model_key = new BShopSkuModelKey();
            $mkAdd['m_id']        = $params['m_id'];
            $mkAdd['k_id']        = $kVal;
            if (!$b_shop_sku_model_key->save($mkAdd)) {
                $this->dbMaster->rollback();
                $this->fail(-1, '模型规格关联失败!');
            }
        }
        $this->dbMaster->commit();
        $this->ok('操作成功!');
    }

    /**
     * 模型分类
     */
    public function modelListAction()
    {
        $BShopUserInfoDb = new BshopUsersInfo();
        $b_shop_user_info = $BShopUserInfoDb->findFirstByShopId($this->user_admin['id']);
        $BShopGoodsCategoryDb = new BShopGoodsCategory();
        if($b_shop_user_info->category_id){
            $b_shop_goods_category = $BShopGoodsCategoryDb->findFirstById($b_shop_user_info->category_id);
            if($b_shop_goods_category){
                $model_ids = $b_shop_goods_category->model_ids;
            }else{
                $model_ids = "-1";
            }
        }else{
            $model_ids="-1";
        }
        $db   = new BShopSkuModel();
        $list = $db->find(array(
            "conditions"=>"id in ({$model_ids})"
        ))->toarray();
        foreach($list as $key=>$value){
            $list[$key]['id']=(int)$value['id'];
        }
        $this->ok($list);
    }

    /**
     * 模型详情
     */
    public function modelDetailsAction()
    {
        if (!isset($this->params['m_id']) || empty($this->params['m_id'])) {
            $this->fail(-1, '缺少参数m_id');
        }
        $ShopGoodsServices = new ShopgoodsServices();
        $getList = $ShopGoodsServices->modelDetails($this->params['m_id'],$this->params['shop_id']);
        $this->ok($getList);
    }



    /**
     * 库存预警
     */
    public function earlystockgoodsAction(){
        if(!isset($this->params['page']) || empty($this->params['page'])){
            $this->params['page'] = 1;
        }
        if(!isset($this->params['limit']) || empty($this->params['limit'])){
            $this->params['limit']=10;
        }
        $BShopAppConfigDb = new BShopAppConfig();
        $b_shop_app_shop = $BShopAppConfigDb->find_list("stock_warning",$this->user_admin['id']);
        if(!isset($b_shop_app_shop['stock_warning']) || empty($b_shop_app_shop['stock_warning'])){
            $b_shop_app_shop['stock_warning'] = 20;
        }

        $this->params['stock'] = $b_shop_app_shop['stock_warning'];
        $this->params['shop_id'] = $this->user_admin['id'];

        $BShopGoodsSkuDb = new BShopGoodsSku();
        $get_list = $BShopGoodsSkuDb->get_list($this->params);
        $this->ok($get_list);
    }



    /**
     * 库存预警
     */
    public function goodsstockAction(){
        if(!isset($this->params['page']) || empty($this->params['page'])){
            $this->params['page'] = 1;
        }
        if(!isset($this->params['limit']) || empty($this->params['limit'])){
            $this->params['limit']=10;
        }
        $this->params['shop_id'] = $this->user_admin['id'];

        $BShopGoodsSkuDb = new BShopGoodsSku();
        $get_list = $BShopGoodsSkuDb->get_list($this->params);
        $this->ok($get_list);
    }


    /**
     * 修改库存
     */
    public function update_stockAction(){
        if(isset($this->params['sku_id']) && !empty($this->params['sku_id'])){
            if(!isset($this->params['sku_stock']) || empty($this->params['sku_stock'])){
                $this->fail(-1,'输入的库存不能为空');
            }else{
                if(!preg_match('/^([1-9][0-9]*){1,10}$/',$this->params['sku_stock'])){
                    $this->fail(-1,'库存只能是正整数');
                }
            }
            $BShopGoodsSkuDb = new BShopGoodsSku();
            $b_shop_goods_sku = $BShopGoodsSkuDb->findFirstById($this->params['sku_id']);
            if(!$b_shop_goods_sku){
                $this->fail(-1,'没有找到记录行');
            }
            $b_shop_goods_sku->stock = $this->params['sku_stock'];
            $b_shop_goods_sku->updated_at = date('Y-m-d H:i:s');
            if($b_shop_goods_sku->save()){
               $this->ok([]);
            }
        }else{
            if(!isset($this->params['stock']) || empty($this->params['stock'])){
                $this->fail(-1,'输入的库存不能为空');
            }else{
                if(!preg_match('/^([1-9][0-9]*){1,10}$/',$this->params['stock'])){
                    $this->fail(-1,'库存只能是正整数');
                }
            }
            $BShopGoodsDb = new BShopGoods();
            $b_shop_goods = $BShopGoodsDb->findFirstById($this->params['id']);
            if(!$b_shop_goods){
                $this->fail(-1,'没有找到记录行');
            }
            $b_shop_goods->stock = $this->params['stock'];
            $b_shop_goods->updated_at = date('Y-m-d H:i:s');
            if($b_shop_goods->save()){
                $this->ok([]);
            }
        }
        $this->fail(-1,'更新失败');
    }



    /**
     * 规格编辑验证
     * @param $data
     * @return bool|string
     */
    private function verification($data)
    {
        if (!isset($data['model_name']) || empty($data['model_name'])) {
            return '缺少参数model_name!';
        }
        if (!isset($data['list']) || empty($data['list'])) {
            return '缺少参数list!';
        }
        foreach ($data['list'] as $val) {
            //$val = json_decode($val, true);
            if (!isset($val['key_name']) || empty($val['key_name'])) {
                return '规格名不能为空!';
            }
            if (!isset($val['value']) || empty($val['value'])) {
                return '规格值不能为空!';
            }
            foreach ($val['value'] as $vVal) {
                if (empty($vVal['value_name'])) {
                    return '请填写规格!' . $val['value'] . '的所有值';
                }
            }
        }
        return true;
    }
}
